package com.lemon.smartsafetynew.ui.activity.patrol;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.BindNfcEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafety.tag.DefaultCode;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemBindNfcActivity;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.event.common.CountEvent;
import com.lemon.smartsafetynew.entity.event.common.TypeEvent;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolTaskItemListVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolTaskItemVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolTaskVo;
import com.lemon.smartsafetynew.net.services.SafePatrolServices;
import com.lemon.smartsafetynew.ui.activity.qrcode.CodeUtils;
import com.lemon.smartsafetynew.ui.activity.qrcode.QRcodeActivity;
import com.lemon.smartsafetynew.ui.adapter.patrol.PatrolTaskItemAdapter;
import com.lemon.smartsafetynew.util.common.CallUtils;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.patrol.CheckItemUtil;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.permission.EasyPermissions;
import kale.adapter.LemonRcvAdapter;

/**
 * Created by Andrew on 2017/8/1.
 */

public class SafePatrolTaskDetailActivity extends SwipeBackActivity
        implements RecyclerTClickListener<SafePatrolTaskItemVo> {

    @Bind(R.id.count_time)
    TextView countTime;
    @Bind(R.id.title_layout)
    LinearLayout titleLayout;
    @Bind(R.id.cancel_patrol_btn)
    Button cancelPatrolBtn;
    @Bind(R.id.start_patrol_btn)
    Button startPatrolBtn;

    @Bind(R.id.normal_tv)
    TextView normalTv;
    @Bind(R.id.abnormal_tv)
    TextView abnormalTv;
    @Bind(R.id.need_check_tv)
    TextView needCheckTv;

    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView mMultiStateView;
    @Bind(R.id.check_item_status_bar)
    LinearLayout checkItemStatusBar;

    // =================== 上个页面传过来的Bundle数据 ===================
    private static SafePatrolTaskVo safePatrolTaskVo = null;

    // =================== 非变量 ===================
    private SafePatrolTaskItemVo taskItemVo = null;

    // =================== RecyclerView ===================
    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
    protected int pageSize = Constants.PAGE_SIZE;
    public List<SafePatrolTaskItemVo> mDataList = new ArrayList<>();
    protected LemonRcvAdapter<SafePatrolTaskItemVo> mAdapter;

    // =================== 定时器 ======================
    private Timer timer;
    private int totalTime = 0;

    // =================== 开关量 ======================
    private boolean taskStart = false;
    private boolean firstTime = true;


    @Override
    protected void initTitle() {
        this.setBarTitle("巡查路线");
    }

    @Override
    protected void callFinish() {

        if ("结束巡查".equals(startPatrolBtn.getText().toString().trim())) {
            showDialog("您当前正在巡查，请先结束巡查，然后离开。");
        } else {
            AppService.getBus().post(new TypeEvent()); //call页面刷新
            AppManager.getAppManager().finishActivity(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_patrol_task_detail;
    }

    /**
     * 下拉刷新
     */
    public void onPullRefresh() {

        if (safePatrolTaskVo == null) {
            return;
        }

        LemonRequestParams params = new LemonRequestParams("");
        params.put("task_id", safePatrolTaskVo.getF_id());
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        SafePatrolServices
                .init()
                .getSafePatrolTask(RefreshType.REFRESH, params);

    }

    /**
     * 上拉加载
     */
    public void onLoadMore() {

        if (safePatrolTaskVo == null) {
            return;
        }

        LemonRequestParams params = new LemonRequestParams("");
        params.put("task_id", safePatrolTaskVo.getF_id());
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        SafePatrolServices
                .init()
                .getSafePatrolTask(RefreshType.LOAD_MORE, params);

    }

    @Override
    protected void getBundleArgs() {

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            safePatrolTaskVo = (SafePatrolTaskVo) bundle.get(KeyConstants.KEY_SAFE_PATROL_TASK);
        }
    }


    @Override
    protected void initViews() {
        super.initViews();

        initData();

        // ========= RecycleView =========
        final LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadMore();
            }
        });

        mMultiStateView.setErrorRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });

//        mPullToRefreshRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                int item = layoutManager.findFirstVisibleItemPosition();
//
//                //TODO
//                Log.e("yxy", "item = " + item);
//                Log.e("yxy", "newState = " + newState);
//
//                if (item <= 1) {
//                    titleLayout.setVisibility(View.VISIBLE);
//                } else {
//                    titleLayout.setVisibility(View.GONE);
//                }
//            }
//        });


        // ======= 初始化title =======
        initSafeTaskTitle();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!firstTime) {
            callRefresh();
        }
        firstTime = false;
    }

    /**
     * 页面展示数据
     */
    private void initSafeTaskTitle() {

        try {

            LinearLayout taskName = (LinearLayout) titleLayout.getChildAt(0);
            LinearLayout taskPerson = (LinearLayout) titleLayout.getChildAt(1);
            LinearLayout taskDate = (LinearLayout) titleLayout.getChildAt(2);
            LinearLayout taskTime = (LinearLayout) titleLayout.getChildAt(3);

            taskName.setBackgroundResource(R.color.color_label_bg);
            taskDate.setBackgroundResource(R.color.color_label_bg);


            TextView taskNameLabel = (TextView) taskName.getChildAt(0);
            TextView taskPersonLabel = (TextView) taskPerson.getChildAt(0);
            TextView taskDateLabel = (TextView) taskDate.getChildAt(0);
            TextView taskTimeLabel = (TextView) taskTime.getChildAt(0);

            TextView taskNameTv = (TextView) taskName.getChildAt(1);
            TextView taskPersonTv = (TextView) taskPerson.getChildAt(1);
            TextView taskDateTv = (TextView) taskDate.getChildAt(1);
            TextView taskTimeTv = (TextView) taskTime.getChildAt(1);

            taskNameLabel.setText("路线名称：");
            taskPersonLabel.setText("巡查人员：");
            taskDateLabel.setText("巡查日期：");
            taskTimeLabel.setText("巡查时间：");


            taskNameTv.setText(safePatrolTaskVo.getF_name());
            taskPersonTv.setText(safePatrolTaskVo.getUser_name());
            taskDateTv.setText(CommonUtil.secondToTimeStr(safePatrolTaskVo.getPlan_start_time(), DateTypeEnum.DAY));
            taskTimeTv.setText(CommonUtil.timeToStr2(safePatrolTaskVo.getPlan_start_time()) + " - "
                    + CommonUtil.timeToStr2(safePatrolTaskVo.getPlan_end_time()));

//            TextView taskRemark = (TextView) taskTime.getChildAt(2);
//            taskRemark.setText("查看任务说明");
//            if (StringUtils.isEmpty(safePatrolTaskVo.getF_desc())) {  //TODO 看是用getF_desc 还是getF_remark
//
//                taskRemark.setVisibility(View.VISIBLE);
//                taskRemark.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showDialog(safePatrolTaskVo.getF_desc());
//                    }
//                });
//
//            } else {
//                taskRemark.setVisibility(View.GONE);
//            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化变量
     */
    private void initData() {

        taskStart = false;
    }

    private LemonRcvAdapter<SafePatrolTaskItemVo> getLemonAdapter() {
        return new PatrolTaskItemAdapter(mDataList, this);
    }

    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_SAFE_PATROL_TASK.equals(event.getTag())) { //获取巡查路线的检查项
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && mPullToRefreshRecyclerView != null) {
                RefreshType type = (RefreshType) event.getOther();
                if (RefreshType.REFRESH == type) {
                    mPullToRefreshRecyclerView.onRefreshComplete();
                } else {
                    mPullToRefreshRecyclerView.setFooterComplete();
                }
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefresh((List<SafePatrolTaskItemVo>) event.getObj());
                    } else {
                        httpLoadMore((List<SafePatrolTaskItemVo>) event.getObj());
                    }
                    currentPage++;

                    // ======== 初始化页面状态个数值 =======
                    statusBarView((List<SafePatrolTaskItemVo>) event.getObj());

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    if (RefreshType.REFRESH == type) {
                        httpRefreshError(event.getMsg());
                    } else {
                        httpLoadMoreError(event.getMsg());
                    }
                }
            }
        } else if (KeyConstants.URL_START_PATROL_TASK.equals(event.getTag())) {  //开始巡查
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    startTaskView();

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });

                }
            }
        } else if (KeyConstants.URL_FINISH_PATROL_TASK.equals(event.getTag())) { //结束巡查
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    finishTaskView();

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    //TODO
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            //callFinish();
                        }
                    });
                }
            }
        }
    }


    // =================== RecyclerView 上拉刷新，下拉加载  begin ===================
    public void httpRefresh(List<SafePatrolTaskItemVo> data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                //mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    public void httpLoadMore(List<SafePatrolTaskItemVo> data) {
        if (data != null && !data.isEmpty()) {
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mAdapter.addItems(data);
        }
    }

    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }

    public void httpLoadMoreError(String msg) {
        //mHUDUtil.showErrorTip(msg);
    }
    // =================== RecyclerView 上拉刷新，下拉加载 end ===================


    /**
     * RecyclerView 中的检查项点击事件
     *
     * @param data
     * @param position
     */
    @Override
    public void onItemClick(SafePatrolTaskItemVo data, int position) {

        taskItemVo = data;

        if(CheckItemUtil.isNFCMust(data.getNfc_must()) && !StringUtils.isEmpty(data.getNfc_code())) {//必须使用NFC检查且NFC值不为空
            startNfc();
        } else if (!StringUtils.isEmpty(data.getNfc_code()) && !StringUtils.isEmpty(data.getQrcode_code())) {  //NFC和QR都不为null
            showChooseDialog("请选择检查方式");
        } else if (!StringUtils.isEmpty(data.getNfc_code())) {  //NFC不为null
            startNfc();
        } else if (!StringUtils.isEmpty(data.getQrcode_code())) { //QR不为null
            startQrcode();
        } else {
            showDetailActivity();
        }

    }

    /**
     * 跳转检查项详细的检查页面
     */
    private void showDetailActivity() {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_ITEM_TASK, taskItemVo);
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID, safePatrolTaskVo.getF_id());
        bundle.putString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW, "");// taskId 根据任务iD进行巡检
        UIHelper.showActivity(SafePatrolTaskDetailActivity.this, bundle, SafePatrolCheckItemActivity.class);
    }

    @OnClick({R.id.cancel_patrol_btn, R.id.start_patrol_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancel_patrol_btn:
                //TODO
                break;
            case R.id.start_patrol_btn:
                taskStart = !taskStart;
                if (taskStart) {
                    callStartTask();
                } else {
                    callFinishTask();
                }
                break;
        }
    }

    /**
     * 检查项刷新请求
     */
    private void callRefresh() {
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.beginRefreshing();
    }

    /**
     * 开始任务网络请求
     */
    private void callStartTask() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("task_id", safePatrolTaskVo.getF_id());

        SafePatrolServices
                .init()
                .startPatrolTask(params);
    }

    /**
     * 结束任务网络请求
     */
    private void callFinishTask() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("task_id", safePatrolTaskVo.getF_id());

        SafePatrolServices
                .init()
                .finishPatrolTask(params);
    }

    /**
     * 开始任务成功后，页面展示
     */
    private void startTaskView() {

        titleLayout.setVisibility(View.GONE);
        mMultiStateView.setVisibility(View.VISIBLE);
        mPullToRefreshRecyclerView.setVisibility(View.VISIBLE);
        checkItemStatusBar.setVisibility(View.VISIBLE);

        startPatrolBtn.setBackgroundResource(R.drawable.selector_red_button);
        startPatrolBtn.setText("结束巡查");

        countTime();
        callRefresh();
    }

    /**
     * 结束任务成功后，退出页面
     */
    private void finishTaskView() {

//        // ========= 结束巡查点击成功后,离开页面 ===========
//        AppService.getBus().post(new TypeEvent()); //call页面刷新
//        AppManager.getAppManager().finishActivity(this);

        // ========= 结束巡查点击成功后, 进入本次巡查结果页面 ===========
        //AppService.getBus().post(new TypeEvent()); //call页面刷新

        SafePatrolTaskItemListVo safePatrolTaskItemListVo = new SafePatrolTaskItemListVo();

        List<SafePatrolTaskItemVo> list = new ArrayList<>();

        for (SafePatrolTaskItemVo safePatrolTaskItemVo : mDataList) {
            if (safePatrolTaskItemVo.getStatus() == 2) {
                list.add(safePatrolTaskItemVo);
            }
        }

        safePatrolTaskItemListVo.setSafePatrolTaskItemVos(list);

        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_TASK, safePatrolTaskVo);
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_TASK_CHECK_ITEM_LIST, safePatrolTaskItemListVo);
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_TASK_DURING_TIME, totalTime);
        UIHelper.showActivity(SafePatrolTaskDetailActivity.this, bundle, SafePatrolResultActivity.class);
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 巡查路线当前检查项的状态统计和页面展示
     *
     * @param data
     */
    private void statusBarView(List<SafePatrolTaskItemVo> data) {

        //checkItemStatusBar.setVisibility(View.VISIBLE);
        int normal = 0;
        int abnormal = 0;
        int not_check = 0;

        for (SafePatrolTaskItemVo taskItemVo : data) {
            if (taskItemVo.getStatus() == 1) {
                normal++;
            } else if (taskItemVo.getStatus() == 2) {
                abnormal++;
            } else {
                not_check++;
            }

        }

        normalTv.setText("正常：" + normal);
        abnormalTv.setText("异常：" + abnormal);
        needCheckTv.setText("待查：" + not_check);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        //getMenuInflater().inflate(R.menu.menu_filter, menu);
        //getMenuInflater().inflate(R.menu.menu_qrcode, menu);
        //getMenuInflater().inflate(R.menu.menu_nfc, menu);
        getMenuInflater().inflate(R.menu.menu_phone, menu);

        return menuResult;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    /*    if (item.getItemId() == R.id.action_filter) {
            showPopWindow();
        }*/
        if (item.getItemId() == R.id.action_qrcode) {
            if (getOpenCameraEasyPermissions()) {
                startQrcode();
            }
        }
        if (item.getItemId() == R.id.action_nfc) {
            startNfc();
        }
        if (item.getItemId() == R.id.action_call_phone) {
            //TODO 紧急联系人电话
            User user = AccountUtil.getUser();
            if (user != null) {

                if (user.getEmergencyPhone() != null) {
                    CallUtils.callTel(user.getEmergencyPhone());
                } else if (user.getCoMobile() != null) {
                    CallUtils.callTel(user.getCoMobile());
                } else {
                    mHUDUtil.showErrorTip("公司无紧急联系人电话", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        }


        return super.onOptionsItemSelected(item);
    }

    /**
     * 跳转NFC 读取页面
     */
    private void startNfc() {
        Bundle bundle = new Bundle();
        bundle.putString(BaseTAG.COMMON_BASE_TAG, SafePatrolTaskDetailActivity.class.getName());
        UIHelper.showActivity(this, bundle, BuildingCheckItemBindNfcActivity.class);
    }


    /**
     * 跳转QR code 读取页面
     */
    private void startQrcode() {
        try {
            //Intent intent = new Intent(this, CaptureActivity.class);
            Intent intent = new Intent(this, QRcodeActivity.class);
            startActivityForResult(intent, DefaultCode.REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 不知为何 华为手机申请摄像头权限会崩溃
     */
    private boolean getOpenCameraEasyPermissions() {

        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            return true;
        } else {
            ToastUtil.show("请允许摄像头权限");
            return false;
        }

    }

    /**
     * QR code读取结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == DefaultCode.REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.LOGE("解析结果:" + result);

                    if (taskItemVo.getQrcode_code().equals(result)) { //二维码匹配成功
                        showDetailActivity();
                    } else { //二维码匹配失败
                        showDialog("二维码匹配失败");
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtils.toastMsg("解析二维码失败");
                }
            }
        }

    }

    /**
     * NFC 读取结果
     */
    @Subscribe
    public void onEventMainThread(final BindNfcEvent event) {
        if (SafePatrolTaskDetailActivity.class.getName().equals(event.getTag())) {
            if (!com.lemon.smartsafety.utils.CommonUtil.strIsEmpty(event.getCode())) {
                LogUtils.LOGE("巡查NFC:" + event.getCode());

                if (taskItemVo.getNfc_code().equals(event.getCode())) { //NFC匹配成功
                    showDetailActivity();
                } else { //NFC匹配失败
                    showDialog("NFC匹配失败");
                }
            }
        }
    }

    /**
     * 页面计时器
     */
    private void countTime() {

        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                totalTime++;
                AppService.getBus().post(new CountEvent());
            }
        }, 0, 1000);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CountEvent event) {
        countTime.setText(CommonUtil.formatTime(totalTime));
    }


    /**
     * 选择检查项是二维码还是NFC
     */
    private MaterialDialog chooseDialog;

    private void showChooseDialog(String remark) {
        chooseDialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content(remark)
                .negativeText("触碰NFC")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        startNfc();
                    }
                })
                .positiveText("扫描二维码")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        startQrcode();
                    }
                })
                .show();
    }

    /**
     * Dialog
     */
    private MaterialDialog materialDialog;

    private void showDialog(String remark) {
        materialDialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content(remark)
                .positiveText(android.R.string.ok)
                .show();
    }

    private void cancelDialog() {

        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }

        if (chooseDialog != null && chooseDialog.isShowing()) {
            chooseDialog.dismiss();
            chooseDialog = null;
        }
    }

    /**
     * 清理对象，缓存等
     */
    private void clear() {

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }

        cancelDialog();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        clear();
    }

}
